const passport = require('passport');
const LocalStrategy = require('passport-local');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const bcrypt = require('bcrypt');

// const User = require('../models/user.model');
const userCtrl = require('../controllers/user.controller') 
const config = require('./config');

const localLogin = new LocalStrategy({
  usernameField: 'username'
}, async (username, password, done) => {
  console.log(username)
  let user = await userCtrl.findByUsername(username);
  if (!user || !bcrypt.compareSync(password, user.password)) {
    console.log('error')
    return done(null, false, { message: 'Your login details could not be verified. Please try again.' });
  }
  // user = user.toObject();
  // delete user.hashedPassword;
  done(null, user);
});

const jwtLogin = new JwtStrategy({
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: config.jwtSecret
}, async (payload, done) => {
  let user = await userCtrl.findById(payload.id);
  if (!user) {
    return done(null, false);
  }
  // user = user.toObject();
  // delete user.hashedPassword;
  done(null, user);
});

passport.use(localLogin);
passport.use(jwtLogin);

module.exports = passport;
